#!/usr/bin/env bash

set -eu
set -o pipefail

MASON_VERSION="v0.14.2"
PROTOBUF_VERSION="3.3.0"

mkdir -p ./mason

if [[ ! -f ./mason/mason ]]; then
    curl -sSfL https://github.com/mapbox/mason/archive/${MASON_VERSION}.tar.gz | tar --gunzip --extract --strip-components=1 --exclude="*md" --exclude="test*" --directory=./mason
fi


if [[ ! -f ./mason_packages/.link/bin/protoc ]]; then
    ./mason/mason install protobuf ${PROTOBUF_VERSION}
    ./mason/mason link protobuf ${PROTOBUF_VERSION}
fi

function decode() {
  ./mason_packages/.link/bin/protoc \
    vector-tile-spec/2.1/vector_tile.proto \
    --decode vector_tile.Tile \
    < ${1}
}

function decode_raw() {
  ./mason_packages/.link/bin/protoc --decode_raw \
  < ${1}
}

RAW=false

# https://stackoverflow.com/questions/192249/how-do-i-parse-command-line-arguments-in-bash
for i in "$@"
do
case $i in
    --raw)
    RAW=true
    shift
    ;;
    *)
    FIXTURE="$1"
    ;;
esac
done

if [ -z "${FIXTURE-}" ]; then
  echo "please pass the path to a mvt fixture to decode"
  exit 1
fi

if [[ $RAW = true ]]; then
  decode_raw ${FIXTURE}
else
  decode ${FIXTURE}
fi
